package com.kefu.admin.common.zk.zkleader;

import com.kefu.admin.common.globals.ApplicationConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Role;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * Created by TWD on 2018/9/29.
 */
@EnableScheduling
public class SchedulerConfiguration  implements SchedulingConfigurer {

    public SchedulerConfiguration() {
    }

    @Bean
    public ZkSchedulerCoordinator zkSchedulerCoordinator(ApplicationConstant applicationConstant) {
        return new ZkSchedulerCoordinator(applicationConstant);
    }

    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        TaskScheduler taskScheduler = new ConcurrentTaskScheduler(this.scheduledExecutorService(ApplicationContextHolder.constant));
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

    @Bean(
            name = {"org.springframework.context.annotation.internalScheduledAnnotationProcessor"}
    )
    @Role(2)
    @Primary
    public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor(ZkSchedulerCoordinator zkSchedulerCoordinator) {
        return new ZkScheduledAnnotationBeanPostProcessor(zkSchedulerCoordinator);
    }

    @Bean(
            destroyMethod = "shutdown"
    )
    public ScheduledExecutorService scheduledExecutorService(ApplicationConstant applicationConstant) {
        return new ScheduledThreadPoolExecutor(applicationConstant.schedulerThreadCount);

    }
}
